package pap.initialization;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;

import pap.Point;
import pap.Vector;
import pap.bodies.Body;
import pap.bodies.SimpleBody;

public class FileBodyInitializer implements IBodyInitializer {

	String fileName;
	List<Body> bodies;

	public FileBodyInitializer(String fileName) {
		this.fileName = fileName;
	}

	@Override
	public List<Body> initAndGetBodies() {
		bodies = new ArrayList<Body>();

		readFile();

		return bodies;
	}

	/**
	 * Reads the bodies from file.
	 */
	private void readFile() {

		JSONParser parser = new JSONParser();

		try {
			JSONArray jsArray = (JSONArray) parser.parse(new FileReader(
					fileName));

			for (Object o : jsArray) {
				JSONObject jsonObject = (JSONObject) o;

				double mass = (Double) jsonObject.get("mass");

				JSONArray jSpeed = (JSONArray) jsonObject.get("speed");
				Iterator<Double> speedIterator = jSpeed.iterator();

				double degrees = speedIterator.next();

				double magnitude = speedIterator.next();

				Vector speed = new Vector(degrees, magnitude);

				JSONArray jPos = (JSONArray) jsonObject.get("position");
				Iterator<Double> posIterator = jPos.iterator();
				double[] coordinates = new double[jPos.size()];

				for (int i = 0; posIterator.hasNext(); i++) {
					coordinates[i] = posIterator.next();
				}

				Point position = new Point(coordinates);

				bodies.add(new SimpleBody(mass, position, speed));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
